package com.agileai.hotweb.controller.core;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.bizmoduler.core.TreeAndContentManage;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.MapUtil;

public class TreeAndContentColumnEditHandler extends BaseHandler{
 	protected String columnIdField = null;
	protected String columnParentIdField = null;
	
    public TreeAndContentColumnEditHandler() {
        super();
    }
	
    public ViewRenderer prepareDisplay(DataParam param) {
		String currentId = null;
		String operaType = param.get(OperaType.KEY);
		if (OperaType.CREATE.equals(operaType)){
			currentId = param.get(this.columnParentIdField);
			this.setAttribute(this.columnParentIdField, currentId);
		}
		else if (OperaType.UPDATE.equals(operaType)){
			DataRow record = getService().queryTreeRecord(param);
			this.setAttributes(record);	
		}
		this.setOperaType(operaType);
		processPageAttributes(param);
		return new LocalRenderer(getPage());
	}
	
	public ViewRenderer doSaveAction(DataParam param){
		String operateType = param.get(OperaType.KEY);
		if (OperaType.CREATE.equals(operateType)){
			getService().createTreeRecord(param);	
		}
		else if (OperaType.UPDATE.equals(operateType)){
			getService().updateTreeRecord(param);	
		}
		return new AjaxRenderer(SUCCESS);
	}
	
	public ViewRenderer doCheckUniqueAction(DataParam param){
		String responseText = "";
		String operateType = param.get(OperaType.KEY);
		DataRow record = getService().queryTreeRecord(param);
		if (OperaType.CREATE.equals(operateType)){
			if (!MapUtil.isNullOrEmpty(record)){
				responseText = defDuplicateMsg;
			}			
		}else if (OperaType.UPDATE.equals(operateType)){
			String columnId = param.get(columnIdField);
			if (!MapUtil.isNullOrEmpty(record) && !columnId.equals(record.stringValue(columnIdField))){
				responseText = defDuplicateMsg;
			}
		}
		return new AjaxRenderer(responseText);
	}
	
    protected TreeAndContentManage getService() {
        return (TreeAndContentManage) this.lookupService(this.getServiceId());
    }
}